#include "vglwindow.h"

#include <QSystemTrayIcon>
#include <QAction>
#include <QApplication>
#include <QMenu>
#include <QMutex>
#include <QFileInfo>
//#include <QProcess>
#include <cstdlib>

Window::Window()
{
    this->resize(1,1);
    this->setX(-1);
    this->setY(-1);
    this->setFlag(Qt::FramelessWindowHint);
    this->hide();
}

Window::~Window()
{

}

void Window::initializeGL()
{
    initializeOpenGLFunctions();
    QString CardName=QString((char*)glGetString(GL_VENDOR));
    QString CardRender=QString((char*)glGetString(GL_RENDERER));
    QString CardVersion=QString((char*)glGetString(GL_VERSION));

    if(CardName.toLower().indexOf("nvidia")!=-1 || CardName.toLower().indexOf("nouveau")!=-1)
    {
            QSystemTrayIcon *TrayIcon= new QSystemTrayIcon(this);
           TrayIcon->setIcon(this->icon());

           QAction* quitAction = new QAction("关闭设备锁", this);
           connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));

           QMenu *trayIconMenu = new QMenu();
           trayIconMenu->addAction("OpenGL厂商："+CardName)->setDisabled(true);
           trayIconMenu->addAction("OpenGL设备："+CardRender)->setDisabled(true);
           trayIconMenu->addSeparator();
           trayIconMenu->addAction(quitAction);
           TrayIcon->setContextMenu(trayIconMenu); //添加右键菜单
           TrayIcon->show();
    }else
    {
        QString FPath="";
        QFileInfo fileInfo("/bin/optirun");
        if(fileInfo.isFile())
        {
            FPath="/bin/optirun";
        }else
        {
            QFileInfo fileInfo("/usr/bin/optirun");
            if(fileInfo.isFile())
            {
                FPath="/usr/bin/optirun";
            }else
            {
                QFileInfo fileInfo("/usr/local/bin/optirun");
                if(fileInfo.isFile())
                {
                    FPath="/usr/local/bin/optirun";
                }else
                {

                    QFileInfo fileInfo("/sbin/optirun");
                    if(fileInfo.isFile())
                    {
                        FPath="/sbin/optirun";
                    }else
                    {

                        QFileInfo fileInfo("/usr/sbin/optirun");
                        if(fileInfo.isFile())
                        {
                            FPath="/usr/sbin/optirun";
                        }
                    }
                }
            }
        }
        if(FPath!="")
        {
            QString APath=QApplication::applicationFilePath();
            //QProcess p(0);
            //QString args;
            //args.append(APath);
            QString cmd="sleep 1;\""+FPath+"\" \""+APath+"\";";
            system(cmd.toLocal8Bit());
            //system("sleep 2;\""+FPath+"\" \""+APath+"\";");
        }
        QApplication::exit();
    }
}

void Window::resizeGL(int w, int h)
{
    Q_UNUSED(w);
    Q_UNUSED(h);
}

void Window::paintGL()
{
}
